package com.yzh.croom.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yzh.croom.model.domain.*;
import com.yzh.croom.service.*;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/teacher")
public class TeacherController {

    @Autowired
    private MessageService messageService;
    @Autowired
    private RoomService roomService;
    @Autowired
    private VroomService vroomService;
    @Autowired
    private WeekService weekService;
    @Autowired
    private CourseTimeService courseTimeService;

    @GetMapping("/toUnReadMessage")
    public String toMessage(Model model,
                            @RequestParam(defaultValue = "1") int pageNum) {
        PageHelper.startPage(pageNum,5);
        String account = getAccount();
        int status = 0;
        List<Message> messages = messageService.getMessageByAccountAndStatus(account,status);
        PageInfo<Message> pageInfo = new PageInfo<Message>(messages);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("tumessages", messages);
        return "teacher/messgaeunread";
    }

    @GetMapping("/toIsReadMessage")
    public String toIsReadMessage(Model model ,
                                  @RequestParam(defaultValue = "1") int pageNum){

        String account = getAccount();
        PageHelper.startPage(pageNum,5);
        int status = 1;
        List<Message> messages = messageService.getMessageByAccountAndStatus(account,status);
        PageInfo<Message> pageInfo = new PageInfo<Message>(messages);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("tsmessages", messages);
        return "teacher/messageisread";
    }

    @GetMapping("/toRoom")
    public String toRoom(Model model,
                         @RequestParam(defaultValue = "1") int pageNum) {
        PageHelper.startPage(pageNum,5);
        List<Room> rs = roomService.getAllRoom();
        PageInfo<Room> pageInfo = new PageInfo<Room>(rs);
        model.addAttribute("toRoompageInfo",pageInfo);
        model.addAttribute("rooms", rs);
        return "teacher/room";
    }

    @GetMapping("/toVroom")
    public String toVroom(Model model,
                          @RequestParam(defaultValue = "1") int pageNum) {
        PageHelper.startPage(pageNum,5);
        List<VRoom> vRooms = vroomService.getVroom();
        PageInfo<VRoom> pageInfo = new PageInfo<VRoom>(vRooms);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("vrooms", vRooms);
        return "teacher/vroom";
    }

    @GetMapping("/openRoomInfo")
    public String openRoomInfo(Model model,String roomId){
        List<VRoom> rooms = vroomService.getVroomById(roomId);
        model.addAttribute("roomInfos",rooms);
        return "teacher/roominfo";
    }

    @GetMapping("/getRoomById")
    public String getRoomById(Model model,
                              String roomId,
                              @RequestParam(defaultValue = "1") int pageNum) {
        PageHelper.startPage(pageNum,5);
        List<VRoom> rooms = vroomService.getVroomById(roomId);
        PageInfo<VRoom> pageInfo = new PageInfo<VRoom>(rooms);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("svroom",rooms);
        return "teacher/svroom";
    }

    @RequestMapping("/deleteMessagesByIds")
    @ResponseBody
    public int deleteMessagesByIds(String[] ids) {
        System.out.println(ids);
        int res = messageService.deleteMessageByIds(ids);
        return res;
    }

    @GetMapping("/openMessage")
    public String openMessage(Model model){
        List<VRoom> vRooms = vroomService.getVRoomGroupById();
        List<Week> weeks = weekService.getAllWeek();
        List<CourseTime> courseTimes = courseTimeService.getCourseTime();
        model.addAttribute("vrooms",vRooms);
        model.addAttribute("weeks",weeks);
        model.addAttribute("times",courseTimes);
        return "teacher/messages";
    }

    @PostMapping("/sendMessage")
    @ResponseBody
    public int sendMessage(@RequestBody Message message){
        message.setAccount(getAccount());
        message.setStatus(0);
        message.setDate(new Date());
        int res = messageService.insertMsg(message);
        return res;
    }

    @GetMapping("/toDownLoad")
    public String toDownLoad(Model model){
        String path = "F:/upload/";
        File fileDir = new File(path);
        File[] files = fileDir.listFiles();
        model.addAttribute("files",files);
        return "teacher/download";
    }

    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(HttpServletRequest request, String filename) throws IOException {
        String path = "F:/upload/";
        File file = new File(path+filename);
        HttpHeaders headers = new HttpHeaders();
        filename=this.getFilename(request,filename);
        headers.setContentDispositionFormData("attachment",filename);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
        }catch (Exception e){
            return new ResponseEntity<>(e.getMessage().getBytes(),HttpStatus.EXPECTATION_FAILED);
        }

    }

    public String getFilename(HttpServletRequest request,String filename) throws UnsupportedEncodingException {
        String [] IEKeytWords = {"MSIE","Trident","Edge"};
        String userAgent = request.getHeader("User-Agent");
        for(String keyWord:IEKeytWords){
            if(userAgent.contains(keyWord)){
                return URLEncoder.encode(filename,"UTF-8");
            }
        }
        return new String (filename.getBytes("UTF-8"),"ISO-8859-1");
    }

    public String getAccount(){
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        UserDetails principal = (UserDetails) authentication.getPrincipal();
        String acount = principal.getUsername();
        return acount;
    }
}
